<script setup>
import { ref, defineEmits } from 'vue'
import { showConfirmDialog } from 'vant'
import { getToken } from '@/utils/user.js'
import api from '@/api/index.js'

const emit = defineEmits(["search"])

const historyList = ref([])

const getHistoryList = () => {
  if (getToken()) {
    apiGetSearchHistoryList()
  } else {
    const listString = localStorage.getItem('historyList')
    if (listString) {
      historyList.value = JSON.parse(listString)
    }
  }
}

const loading = ref(false)
const apiGetSearchHistoryList = () => {
  loading.value = true
  api.getSearchHistoryList().then((res) => {
    const list = res.data.list.filter((item) => item.content)
    historyList.value = list
  }).finally(() => {
    loading.value = false
  })
}

getHistoryList()

const historyClick = (input_key) => {
  emit('search', input_key)
}

const deleteClick = () => {
  showConfirmDialog({
    message:
        '确定清除全部历史记录',
    }).then(() => {
      historyList.value = []
      if (getToken()) {
        deleteHistoryList()
      } else {
        localStorage.setItem('historyList', '[]')
      }
  })
}
const deleteHistoryList = () => {
  api.deleteSearchHistoryList().then((res) => {
    console.log('res', res)
  })
}
</script>

<template>
<div class="history">
  <div v-if="historyList?.length" class="header">
    <h2>搜索历史</h2>
    <img @click="deleteClick" class="delete_icon" src="@/assets/images/icons/DeleteOutlined.jpg" alt="">
  </div>
  <van-skeleton v-if="loading" title :row="2" />
  <ul class="history_list">
    <li
      @click="historyClick(item?.content || item)"
      class="list"
      v-for="(item, index) in historyList"
      :key="index"
    >
      {{ item?.content || item }}
    </li>
  </ul>
</div>
</template>

<style scoped lang="scss">
.history{
  padding: 0 1.5rem;
  .header{
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 2rem;
    padding: .5rem 0 1.2rem 0;
    h2{
      font-size: 1.4rem;
      font-weight: bold;
      color: #333333;
    }
    .delete_icon{
      width: 1.6rem;
      height: 1.6rem;
    }
  }
  .history_list{
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 1rem;
    .list{
      padding: 0 1rem;
      height: 2.8rem;
      background: rgba(0,0,0,0.05);
      border-radius: .5rem;
      opacity: 1;
      font-size: 1.4rem;
      color: #666666;
      line-height: 2.8rem;
      margin-right: 1rem;
      margin-bottom: 1rem;
    }
  }
}
</style>